from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import User
from .serializers import UserRegisterModelSerializer
from .tasks import send_sms

class MobileAPIView(APIView):
    def get(self,request,mobile):
        try:
            user = User.objects.get(mobile=mobile)
            return Response({'errmsg':"当前手机号已经注册"}, status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            return Response({'errmsg':"OK"}, status=status.HTTP_200_OK)

class UserAPIView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserRegisterModelSerializer


from random import randint
from django_redis import get_redis_connection
from django.conf import settings
from .tasks import send_sms

class SMSAPIView(APIView):
    def get(self, request, mobile):
        redis = get_redis_connection('sms_code')
        interval = redis.ttl(f'interval_{mobile}')
        if interval != -2:
            return Response({'errmsg': f"请勿频繁操作，请过{interval}秒再次操作",'interval':interval},status=status.HTTP_400_BAD_REQUEST)
        code = randint(1000, 9999)
        # 从配置中提取信息
        time = settings.RONGLIANYUN.get('sms_expire')
        sms_interval = settings.RONGLIANYUN.get('sms_interval')
        tid = settings.RONGLIANYUN.get('reg_tid')
        send_sms.delay(tid, mobile,(code, time // 60))
        # 开启管道与事务，提高性能
        pipe = redis.pipeline()
        pipe.multi()
        pipe.setex(f'sms_{mobile}', time, code)
        pipe.setex(f'interval_{mobile}', sms_interval, "_")
        pipe.execute()
        return Response({'errmsg': "OK"}, status=status.HTTP_200_OK)